package org.example.scoresystem_backen.service.impl;

import org.example.scoresystem_backen.entity.Class;
import org.example.scoresystem_backen.mapper.ClassMapper;
import org.example.scoresystem_backen.mapper.StudentMapper;
import org.example.scoresystem_backen.mapper.ScoreMapper;
import org.example.scoresystem_backen.service.ClassService;
import org.example.scoresystem_backen.dto.PageRequest;
import org.example.scoresystem_backen.dto.PageResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 班级服务实现类
 */
@Service
@Transactional
public class ClassServiceImpl implements ClassService {

    @Autowired
    private ClassMapper classMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ScoreMapper scoreMapper;
    
    @Override
    public Class createClass(Class clazz) {
        // 检查班级名称和年级组合是否已存在
        if (classMapper.existsByNameAndGrade(clazz.getName(), clazz.getGrade())) {
            throw new RuntimeException("该年级下班级名称已存在");
        }
        classMapper.insert(clazz);
        return clazz;
    }

    @Override
    public Class updateClass(Class clazz) {
        // 检查班级是否存在
        Class existingById = classMapper.findById(clazz.getId());
        if (existingById == null) {
            throw new RuntimeException("班级不存在");
        }

        // 检查班级名称和年级组合是否被其他班级使用
        Class existingClass = classMapper.findByNameAndGrade(clazz.getName(), clazz.getGrade());
        if (existingClass != null && !existingClass.getId().equals(clazz.getId())) {
            throw new RuntimeException("该年级下班级名称已被其他班级使用");
        }

        classMapper.update(clazz);
        return clazz;
    }

    @Override
    public void deleteClass(Integer id) {
        Class clazz = classMapper.findById(id);
        if (clazz == null) {
            throw new RuntimeException("班级不存在");
        }
        // 这里可以添加检查班级下是否还有学生的逻辑
        classMapper.deleteById(id);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Class findById(Integer id) {
        Class clazz = classMapper.findById(id);
        if (clazz != null) {
            return clazz;
        }
        throw new RuntimeException("班级不存在");
    }

    @Override
    @Transactional(readOnly = true)
    public List<Class> findAll() {
        return classMapper.findAll();
    }

    @Override
    @Transactional(readOnly = true)
    public Page<Class> findAll(Pageable pageable) {
        // MyBatis不直接支持分页，这里简化处理
        List<Class> allClasses = classMapper.findAll();
        int start = (int) pageable.getOffset();
        int end = Math.min((start + pageable.getPageSize()), allClasses.size());
        List<Class> pageContent = allClasses.subList(start, end);
        return new PageImpl<>(pageContent, pageable, allClasses.size());
    }

    @Override
    @Transactional(readOnly = true)
    public Class findByNameAndGrade(String name, String grade) {
        Class clazz = classMapper.findByNameAndGrade(name, grade);
        if (clazz != null) {
            return clazz;
        }
        throw new RuntimeException("班级不存在");
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Class> findByGrade(String grade) {
        return classMapper.findByGrade(grade);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Class> findByName(String name) {
        return classMapper.findAllByName(name);
    }

    @Override
    @Transactional(readOnly = true)
    public boolean existsByNameAndGrade(String name, String grade) {
        return classMapper.existsByNameAndGrade(name, grade);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Class> findByGradeContaining(String grade) {
        return classMapper.findByGradeContaining(grade);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Class> findByNameContaining(String name) {
        return classMapper.findByNameContaining(name);
    }

    @Override
    @Transactional(readOnly = true)
    public List<String> findAllGrades() {
        return classMapper.findAllGrades();
    }

    @Override
    @Transactional(readOnly = true)
    public PageResponse<Class> findClassesWithPagination(PageRequest pageRequest, String grade) {
        pageRequest.validate();

        // 查询数据
        List<Class> classes = classMapper.findClassesWithPagination(
            pageRequest.getSearch(),
            grade,
            pageRequest.getOffset(),
            pageRequest.getLimit()
        );

        // 查询总数
        Long totalCount = classMapper.countClassesWithFilter(
            pageRequest.getSearch(),
            grade
        );

        return PageResponse.of(pageRequest, totalCount, classes);
    }

    @Override
    @Transactional
    public Map<String, Object> deleteClassWithCascade(Integer id) {
        // 检查班级是否存在
        Class clazz = classMapper.findById(id);
        if (clazz == null) {
            throw new RuntimeException("班级不存在");
        }

        // 统计要删除的学生数量
        Long studentCount = studentMapper.countByClassId(id);

        // 统计要删除的成绩数量
        Long scoreCount = 0L;
        if (studentCount > 0) {
            scoreCount = scoreMapper.countByClassId(id);

            // 删除成绩记录
            if (scoreCount > 0) {
                scoreMapper.deleteByClassId(id);
            }

            // 删除学生记录
            studentMapper.deleteByClassId(id);
        }

        // 删除班级
        classMapper.deleteById(id);

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("class_id", id);
        result.put("deleted_students_count", studentCount.intValue());
        result.put("deleted_scores_count", scoreCount.intValue());

        return result;
    }
}
